package com.orchard.orchardfarmmanagementsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orchard.orchardfarmmanagementsystem.dto.InventoryInfoDTO;
import com.orchard.orchardfarmmanagementsystem.dto.MaintenanceRecordsDTO;
import com.orchard.orchardfarmmanagementsystem.dto.MaterialDTO;
import com.orchard.orchardfarmmanagementsystem.dto.ResourceOptionDTO;
import com.orchard.orchardfarmmanagementsystem.entity.*;
import com.orchard.orchardfarmmanagementsystem.mapper.*;
import com.orchard.orchardfarmmanagementsystem.service.InventoryService;
import com.orchard.orchardfarmmanagementsystem.service.InventorySupplierService;
import com.orchard.orchardfarmmanagementsystem.service.SuppliesService;
import com.orchard.orchardfarmmanagementsystem.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class InventoryServiceImpl extends ServiceImpl<InventoryMapper, Inventory> implements InventoryService {

    @Autowired
    private InventoryMapper inventoryMapper;

    @Autowired
    private SuppliesMapper suppliesMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private InventorySupplierMapper inventorySupplierMapper;

    public List<InventoryInfoDTO> getAllMaterials() {
        // 查询所有库存记录
        List<Inventory> inventories = inventoryMapper.selectList(null);

        // 提前准备所有需要的材料信息
        List<Integer> materialIds = inventories.stream().map(Inventory::getMaterialId).distinct().collect(Collectors.toList());
        Map<Integer, Materials> materialsMap = suppliesMapper.selectBatchIds(materialIds).stream()
                .collect(Collectors.toMap(Materials::getId, Function.identity()));

        // 准备供应商信息（仅当库存不为0时需要）
        Set<Integer> supplierIds = new HashSet<>();
        for (Inventory inventory : inventories) {
            if (inventory.getCurrentQuantity() > 0) {
                InventorySupplier inventorySupplier = inventorySupplierMapper.selectOne(new QueryWrapper<InventorySupplier>().eq("inventory_id", inventory.getId()));
                if (inventorySupplier != null) {
                    supplierIds.add(inventorySupplier.getSupplierId());
                }
            }
        }
        Map<Integer, Supplier> suppliersMap = supplierMapper.selectBatchIds(new ArrayList<>(supplierIds)).stream()
                .collect(Collectors.toMap(Supplier::getId, Function.identity()));

        List<InventoryInfoDTO> inventoryInfoDTOS = new ArrayList<>();

        for (Inventory inventory : inventories) {
            InventoryInfoDTO inventoryInfoDTO = new InventoryInfoDTO();
            inventoryInfoDTO.setMaterialId(inventory.getMaterialId());
            inventoryInfoDTO.setCurrentQuantity(inventory.getCurrentQuantity());
            inventoryInfoDTO.setThreshold(inventory.getThreshold());

            Materials materials = materialsMap.get(inventory.getMaterialId());
            if (materials != null) {
                inventoryInfoDTO.setMaterialName(materials.getName());
            }

            // 如果库存数量为0，则设置供应商及关联信息为空
            if (inventory.getCurrentQuantity() == 0) {
                inventoryInfoDTO.setSupplierName("无");
                inventoryInfoDTO.setPhone("无");
                inventoryInfoDTO.setPurchaser("无");
                inventoryInfoDTO.setContactPerson("无");
            } else {
                InventorySupplier inventorySupplier = inventorySupplierMapper.selectOne(new QueryWrapper<InventorySupplier>().eq("inventory_id", inventory.getId()));
                if (inventorySupplier != null) {
                    Integer supplierId = inventorySupplier.getSupplierId();
                    Supplier supplier = suppliersMap.get(supplierId);
                    if (supplier != null) {
                        inventoryInfoDTO.setSupplierName(supplier.getName());
                        inventoryInfoDTO.setPhone(supplier.getPhone());
                        inventoryInfoDTO.setContactPerson(supplier.getContactPerson());
                    }
                    inventoryInfoDTO.setPurchaser(inventorySupplier.getPurchaserName());
                }
            }

            inventoryInfoDTOS.add(inventoryInfoDTO);
        }

        return inventoryInfoDTOS;
    }

    @Override
    public List<ResourceOptionDTO> getResourceOptions() {
        // 查询所有库存记录
        List<Inventory> inventories = inventoryMapper.selectList(null);

        // 提前准备所有需要的材料和供应商信息
        List<Integer> materialIds = inventories.stream().map(Inventory::getMaterialId).distinct().collect(Collectors.toList());
        Map<Integer, Materials> materialsMap = suppliesMapper.selectBatchIds(materialIds).stream()
                .collect(Collectors.toMap(Materials::getId, Function.identity()));

        Set<Integer> supplierIds = new HashSet<>();
        for (Inventory inventory : inventories) {
            if (inventory.getCurrentQuantity() > 0) {
                InventorySupplier inventorySupplier = inventorySupplierMapper.selectOne(new QueryWrapper<InventorySupplier>().eq("inventory_id", inventory.getId()));
                if (inventorySupplier != null) {
                    supplierIds.add(inventorySupplier.getSupplierId());
                }
            }
        }
        Map<Integer, Supplier> suppliersMap = supplierMapper.selectBatchIds(new ArrayList<>(supplierIds)).stream()
                .collect(Collectors.toMap(Supplier::getId, Function.identity()));

        List<ResourceOptionDTO> options = new ArrayList<>();

        for (Inventory inventory : inventories) {
            ResourceOptionDTO option = new ResourceOptionDTO();
            option.setMaterialId(inventory.getMaterialId());
            option.setQuantity(inventory.getCurrentQuantity());

            Materials materials = materialsMap.get(inventory.getMaterialId());
            if (materials != null) {
                option.setName(materials.getName());
            }

            // 如果库存数量为0，则设置供应商及关联信息为空
            if (inventory.getCurrentQuantity() == 0) {
                option.setPurchaser("无");
                option.setSupplier(new ResourceOptionDTO.SupplierDTO());
            } else {
                InventorySupplier inventorySupplier = inventorySupplierMapper.selectOne(new QueryWrapper<InventorySupplier>().eq("inventory_id", inventory.getId()));
                if (inventorySupplier != null) {
                    option.setPurchaser(inventorySupplier.getPurchaserName());
                    Integer supplierId = inventorySupplier.getSupplierId();
                    Supplier supplier = suppliersMap.get(supplierId);
                    if (supplier != null) {
                        ResourceOptionDTO.SupplierDTO supplierDTO = new ResourceOptionDTO.SupplierDTO();
                        BeanUtils.copyProperties(supplier, supplierDTO);
                        option.setSupplier(supplierDTO);
                    }
                }
            }

            options.add(option);
        }

        return options;
    }

    @Override
    @Transactional
    public Result updateMaterial(ResourceOptionDTO supplyData) {
        // 检查库存数量是否大于0
        if (supplyData.getQuantity() <= 0) {
            throw new IllegalArgumentException("库存数量必须大于0");
        }

        // 确保提供了有效的材料ID
        if (supplyData.getMaterialId() == null) {
            return Result.error(50001, "材料ID无效");
        }

        // 检查材料是否存在
        Materials material = suppliesMapper.selectById(supplyData.getMaterialId());
        if (material == null) {
            return Result.error(50001, "材料信息无效");
        }

        // 更新库存记录
        Inventory inventory = inventoryMapper.selectOne(new QueryWrapper<Inventory>().eq("material_id",material.getId()));
        if (inventory == null) {
            // 如果没有找到对应的库存记录，则创建新的库存记录
            inventory = new Inventory();
            inventory.setMaterialId(material.getId());
            inventory.setCurrentQuantity(supplyData.getQuantity());
            inventoryMapper.insert(inventory);
        } else {
            // 否则更新现有的库存记录
            Integer updatedQuantity = inventory.getCurrentQuantity() + supplyData.getQuantity();
            inventory.setCurrentQuantity(updatedQuantity);
            inventoryMapper.updateById(inventory);
        }

        // 更新或创建供应商记录
        Supplier supplier = null;
        if (supplyData.getSupplier() != null) {
            supplier = supplierMapper.selectOne(new QueryWrapper<Supplier>().eq("name", supplyData.getSupplier().getName()));
            if (supplier == null) {
                supplier = new Supplier();
                BeanUtils.copyProperties(supplyData.getSupplier(), supplier);
                supplierMapper.insert(supplier);
            } else {
                // 更新现有供应商信息（如果必要）
                BeanUtils.copyProperties(supplyData.getSupplier(), supplier);
                supplierMapper.updateById(supplier);
            }
        }

        // 更新库存-供应商关联记录
        InventorySupplier inventorySupplier = null;
        // 更新库存-供应商关联记录
        if (supplier != null) {
            // 尝试查找现有的关联记录
            inventorySupplier = inventorySupplierMapper.selectOne(
                    new QueryWrapper<InventorySupplier>()
                            .eq("inventory_id", inventory.getId())
            );

            if (inventorySupplier == null) {
                // 如果没有找到对应的关联记录，则创建新的关联记录
                inventorySupplier = new InventorySupplier();
                inventorySupplier.setInventoryId(inventory.getId());
                inventorySupplier.setSupplierId(supplier.getId());
                inventorySupplier.setPurchaserName(supplyData.getPurchaser());

                // 插入新的关联记录
                inventorySupplierMapper.insert(inventorySupplier);
            } else {
                // 更新采购人信息和供应商ID
                inventorySupplier.setPurchaserName(supplyData.getPurchaser());
                inventorySupplier.setSupplierId(supplier.getId());

                // 更新现有的关联记录
                inventorySupplierMapper.updateByInventoryId(inventorySupplier);

            }
        }

        return Result.success("更新库存数量成功");
    }
}


//    public List<InventoryInfoDTO> getAllMaterials() {
//        List<InventoryInfoDTO> inventoryInfoDTOS = new ArrayList<InventoryInfoDTO>();
//        List<Inventory> inventories = inventoryMapper.selectList(null);
//        for (Inventory inventory : inventories) {
//            InventoryInfoDTO inventoryInfoDTO = new InventoryInfoDTO();
//            inventoryInfoDTO.setMaterialId(inventory.getMaterialId());
//            Materials materials = suppliesMapper.selectOne(new QueryWrapper<Materials>().eq("id", inventory.getMaterialId()));
//            inventoryInfoDTO.setMaterialName(materials.getName());
//            inventoryInfoDTO.setThreshold(inventory.getThreshold());
//            inventoryInfoDTO.setCurrentQuantity(inventory.getCurrentQuantity());
//            //设置供应商和用户的信息
//            InventorySupplier inventorySupplier = inventorySupplierMapper.selectOne(new QueryWrapper<InventorySupplier>().eq("inventory_id", inventory.getId()));
//            Integer supplierId = inventorySupplier.getSupplierId();
//            Supplier supplier = supplierMapper.selectOne(new QueryWrapper<Supplier>().eq("id", supplierId));
//            inventoryInfoDTO.setSupplierName(supplier.getName());
//            inventoryInfoDTO.setPhone(supplier.getPhone());
//            inventoryInfoDTO.setPurchaser(inventorySupplier.getPurchaserName());
//            inventoryInfoDTO.setContactPerson(supplier.getContactPerson());
//            inventoryInfoDTOS.add(inventoryInfoDTO);
//
//        }
//        return inventoryInfoDTOS;
//    }
